package com.gp.geits.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gp.geits.Enum.IdentityEnum;
import com.gp.geits.Enum.ResultCodeEnum;
import com.gp.geits.dao.UserDao;
import com.gp.geits.entity.UserEntity;
import com.gp.geits.exception.GETSException;
import com.gp.geits.service.UserService;
import com.gp.geits.utils.*;
import com.gp.geits.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registerByStu(UserEntity userEntity) {
        Long phone = userEntity.getPhone();
        Long stuNo = userEntity.getStuNo();
        String password = userEntity.getPassword();

        //校验参数合法
        if (phone == null || stuNo == null || !StringUtils.hasLength(password)){
            throw new GETSException(ResultCodeEnum.PARAM_ERROR);
        }

        //校验手机号是否存在
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>()
                .eq("phone",phone);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new GETSException(ResultCodeEnum.PHONE_EXISTS);
        }

        //检验学号是否存在
        QueryWrapper<UserEntity> queryWrapper1 = new QueryWrapper<UserEntity>()
                .eq("stu_no", stuNo);
        Integer count1 = baseMapper.selectCount(queryWrapper1);
        if (count1 > 0){
            throw new GETSException(ResultCodeEnum.STUNO_EXISTS);
        }

        UserEntity entity = new UserEntity();
        entity.setPhone(phone);
        entity.setStuNo(stuNo);
        entity.setName(userEntity.getName());
        entity.setPassword(MD5.encrypt(password));
        entity.setIdentity(IdentityEnum.STUDENT.getCode());
        entity.setAvatar("https://gitee.com/c-oe/basic-interview-questions/raw/master/missing-face.png");
        entity.setStatus(0);

        baseMapper.insert(entity);
    }

    @Override
    public void RegisterByComVo(RegisterByComVo vo) {
        Long phone = vo.getPhone();
        String name = vo.getName();
        String password = vo.getPassword();

        //校验参数合法
        if (phone == null || !StringUtils.hasLength(name) || !StringUtils.hasLength(password)){
            throw new GETSException(ResultCodeEnum.PARAM_ERROR);
        }

        //校验手机号是否存在
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>()
                .eq("phone",phone);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0){
            throw new GETSException(ResultCodeEnum.PHONE_EXISTS);
        }

        UserEntity entity = new UserEntity();
        entity.setPhone(phone);
        entity.setName(name);
        entity.setPassword(MD5.encrypt(password));
        entity.setIdentity(IdentityEnum.COMPANY.getCode());
        entity.setAvatar("https://gitee.com/c-oe/basic-interview-questions/raw/master/missing-face.png");

        baseMapper.insert(entity);
    }

    @Override
    public String loginByStu(loginByStuVo loginVo) {

        Long no = loginVo.getNo();
        String password = loginVo.getPassword();

        //校验参数合法
        if (no == null || !StringUtils.hasLength(password)){
            throw new GETSException(ResultCodeEnum.PARAM_ERROR);
        }

        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>()
                .eq("phone", no)
                .or()
                .eq("stu_no", no);

        UserEntity userEntity = baseMapper.selectOne(queryWrapper);
        if (userEntity == null){
            throw new GETSException(ResultCodeEnum.USER_NOT_EXISTS);
        }

        //校验密码正确
        if (!MD5.encrypt(password).equals(userEntity.getPassword())){
            throw new GETSException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //登录：生成token
        JwtInfo info = new JwtInfo();
        info.setNo(userEntity.getStuNo());
        info.setName(userEntity.getName());
        info.setAvatar(userEntity.getAvatar());
        info.setStatus(userEntity.getStatus());

        return JwtUtils.getJwtToken(info,86400);
    }

    @Override
    public String loginByCom(loginByComVo loginVo) {


        Long phone = loginVo.getPhone();
        String password = loginVo.getPassword();

        //校验参数合法
        if (phone == null || !StringUtils.hasLength(password)){
            throw new GETSException(ResultCodeEnum.PARAM_ERROR);
        }

        //校验用户存在
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>()
                .eq("phone", phone);
        UserEntity userEntity = baseMapper.selectOne(queryWrapper);
        if (userEntity == null){
            throw new GETSException(ResultCodeEnum.USER_NOT_EXISTS);
        }

        //校验密码正确
        if (!MD5.encrypt(password).equals(userEntity.getPassword())){
            throw new GETSException(ResultCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //登录：生成token
        JwtInfo info = new JwtInfo();
        info.setNo(userEntity.getPhone());
        info.setName(userEntity.getName());
        info.setAvatar(userEntity.getAvatar());

        return JwtUtils.getJwtToken(info,86400);
    }

    @Override
    public void updatePersonalInformation(UpdatePersonalInformationVo vo, HttpServletRequest request) {

        JwtInfo jwtInfo = loginCheck(request);

        String name = vo.getName();
        String avatar = vo.getAvatar();
        Integer status = vo.getStatus();

        if (StringUtils.hasLength(name) && StringUtils.hasLength(avatar)) {
                baseMapper.updatePersonalInformation1(jwtInfo.getNo(), name, avatar,status);
        }else {
            throw new GETSException(ResultCodeEnum.PARAM_ERROR);
        }

    }


    /**
     * 获取登录信息
     */
    @Override
    public JwtInfo loginCheck(HttpServletRequest request) {
        JwtInfo info;
        try {
            info = JwtUtils.getMemberIdByJwtToken(request);
        } catch (Exception e) {
            throw new GETSException(ResultCodeEnum.LOGIN_AUTH);
        }

        if (info == null) {
            throw new GETSException(ResultCodeEnum.LOGIN_AUTH);
        }
        return info;
    }

    @Override
    public void passwordChange(PasswordChangeVo vo, HttpServletRequest request) {
        //检查是否登录
        JwtInfo info = loginCheck(request);

        UserEntity entity = baseMapper.selectOne(new QueryWrapper<UserEntity>()
                .eq("phone", info.getNo())
                .or()
                .eq("stu_no",info.getNo()));

        if (MD5.encrypt(vo.getOldPassword()).equals(entity.getPassword())){
            entity.setPassword(MD5.encrypt(vo.getNewPassword()));

            baseMapper.updateById(entity);
        }else {
            throw new GETSException(ResultCodeEnum.OLD_PASSWORD_ERROR);
        }
    }
}